package utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Serializable;

public class FileUtil implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	public static void write(String filePath, String fileName, String fileInfo) throws Exception {
		if (!new File(filePath).isDirectory()) {
			new File(filePath).mkdirs();
		}
		File file = new File(filePath, fileName);
		write(file,fileInfo);
	}
	
	public static void write(File file, String fileInfo) throws Exception {
		if (!file.exists()) {
			file.createNewFile();
		}
		BufferedWriter bw = new BufferedWriter(new FileWriter(file, false));
		bw.write(fileInfo);
		bw.flush();
		bw.close();
	}
	
	public static void append(String filePath, String fileName, String fileInfo) throws Exception {
		if (!new File(filePath).isDirectory()) {
			new File(filePath).mkdirs();
		}
		File file = new File(filePath, fileName);
		append(file,fileInfo);
	}
	
	public static void append(File file, String fileInfo) throws Exception {
		if (!file.exists()) {
			file.createNewFile();
		}
		BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
		bw.write(fileInfo);
		bw.flush();
		bw.close();
	}

	public static String read(String filePath, String fileName) throws Exception {
		if (!new File(filePath).isDirectory()) {
			new File(filePath).mkdirs();
		}
		File file = new File(filePath, fileName);
		return read(file);
	}
	
	public static String read(File file) throws Exception {
		if (!file.exists()) {
			file.createNewFile();
		}
		BufferedReader br = new BufferedReader(new FileReader(file));
		StringBuffer sb = new StringBuffer();
		String line = null;
		while ((line = br.readLine()) != null) {
			sb.append(line + System.lineSeparator());
		}
		br.close();
		return sb.toString();
	}
}
